package gov.nasa.anml;

import java.io.File;
import java.io.IOException;

import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;

import gov.nasa.anml.lifted.Domain;
import gov.nasa.anml.parsing.*;
import gov.nasa.anml.parsing.ANMLParser.model_return;
import gov.nasa.anml.utility.SimpleString;

public class Main {
	public static SimpleString dName;
	public static ANMLCharStream input;
	public static boolean readArgs(String args[]) {
		if (args.length == 0) {
			try {
				input = new ANMLInputStream(System.in);
				dName = Domain.defaultName;
				return true;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		
		try {
			File f = new File(args[0]);
			input = new ANMLFileStream(args[0]);
			if (args.length == 1) {
				String name = f.getName();
				int index = name.indexOf('.');
				if (index > 0)
					name = name.substring(0,index);
				dName = new SimpleString(name);
			} else {
				dName = new SimpleString(args[1]);
			}
			return true;
		} catch (IOException e) {
			System.out.println("Provide an anml file as first argument, optionally followed by the desired domain name.  Or use stdin and deal with the name TheDomain.");
			return false;
		}
	}
	
	public static void main(String args[]) {
		if (!readArgs(args)) return;
		
		// create top level for anml and pddl
		// (the anml top level is needed for the parse)
		Domain d = new Domain(dName);
		PDDL pddl = new PDDL();

		// setup character->token, token->tree
		ANMLLexer lex = new ANMLLexer(input);
		CommonTokenStream tokens = new CommonTokenStream(lex);
		ANMLParser parser = new ANMLParser(tokens);		
		ANMLTreeAdaptor adaptor = new ANMLTreeAdaptor(parser.tokenNames);		
		parser.setTreeAdaptor(adaptor);
		
		// do the initial parse
		ANMLParser.model_return r;
		try {
			r = parser.model(d);
			Tree t = (Tree) r.getTree();
			
			// show the AST produced, for debugging
			System.out.println(t.toStringTree());
			System.out.println("\n\n\n\n\n");
	
			// setup tree->anml-model
			CommonTreeNodeStream nodes = new CommonTreeNodeStream(adaptor,t);
			nodes.setTokenStream(tokens);
			ANMLTree walker = new ANMLTree(nodes);
	
			// process the tree
			walker.model(d);
	
			// do anml-model->pddl-model
			d.translate(pddl);
	
			// setup printing the pddl model, anticipating large models
			StringBuilder buf = new StringBuilder(100000);
			
			// do pddl-model->character
			pddl.append(buf);
			// ...and show the result
			System.out.println(buf.toString());
		
		} catch (RecognitionException e) {
			e.printStackTrace();
		}
	}
}
